<template>
  <view class="register-page flex-col">
    <!-- 微信授权加载状态 -->
    <view v-if="authLoading" class="auth-loading flex-col">
      <view class="loading-content flex-col">
        <view class="loading-spinner-wrapper">
          <view class="loading-spinner"></view>
        </view>
        <text class="loading-text">正在获取微信授权...</text>
      </view>
    </view>
    
    <!-- 主要内容 -->
    <view v-else class="main-container flex-row">
      <view class="form-section flex-col">
        <view class="header-group flex-row">
          <text class="app-title">出手鸭</text>
          <text class="page-subtitle">注册工程师账号</text>
        </view>
        
        <!-- 微信授权状态显示 -->
        <view v-if="isWechatEnv && openid" class="auth-status flex-row">
          <text class="auth-success-text">✓ 微信授权成功</text>
        </view>
        
        <view class="name-input-field flex-col">
          <text class="input-label">工程师姓名</text>
          <input 
            v-model="formData.clerkName" 
            class="input-control" 
            type="text" 
            placeholder="请输入工程师姓名"
          />
        </view>
        <view class="phone-input-field flex-col">
          <text class="input-label">工程师电话</text>
          <input 
            v-model="formData.clerkPhone" 
            class="input-control" 
            type="tel" 
            placeholder="请输入手机号码"
            maxlength="11"
            @input="handlePhoneInput"
          />
        </view>
        <button class="submit-button flex-col" @click="handleSubmit" :disabled="loading || !authCode">
          <text class="button-text">{{ loading ? '注册中...' : '注册' }}</text>
        </button>
      </view>
      <view class="spacer-section flex-col"></view>
    </view>
  </view>
</template>

<script>
import { fetchClerkSign, fetchProgramLogin } from '@/api/apiMap/user.js'

export default {
  data() {
    return {
      // 表单数据
      formData: {
        clerkName: '',
        clerkPhone: ''
      },
      // 加载状态
      loading: false,
      // 微信相关数据
      openid: '',
      isWechatEnv: false,
      authLoading: true,
      authCode:""
    }
  },
  
  mounted() {
    this.initWechatAuth()
  },
  methods: {
    // 初始化微信授权
    async initWechatAuth() {
      try {
        console.log('开始初始化微信授权...')
        
        // 检测是否在微信环境中
        const isWechat = this.isInWechat()
        console.log('是否在微信环境:', isWechat)
        
        if (!isWechat) {
          console.log('不在微信环境中，显示提示')
          uni.showModal({
            title: '提示',
            content: '请在微信中打开此页面',
            showCancel: false,
            success: () => {
              // 可以选择跳转到引导页面或其他处理
            }
          })
          this.authLoading = false
          return
        }
        
        this.isWechatEnv = true
        
        // 获取URL中的code参数
        const urlParams = this.getUrlParams()
        const code = urlParams.code
        console.log('URL参数:', urlParams)
        console.log('获取到的code:', code)
        
        if (code) {
          console.log('有code，直接获取openid')
          // 如果有code，直接获取openid
          this.authCode = code
          this.authLoading = false
        } else {
          console.log('没有code，准备跳转到微信授权页面')
          // 如果没有code，跳转到微信授权页面
          this.redirectToWechatAuth()
        }
      } catch (error) {
        console.error('微信授权初始化失败:', error)
        uni.showToast({
          title: '授权失败，请重试',
          icon: 'none'
        })
        this.authLoading = false
      }
    },
    
    // 检测是否在微信环境中
    isInWechat() {
      const ua = navigator.userAgent.toLowerCase()
      return ua.indexOf('micromessenger') !== -1
    },
    
    // 处理手机号码输入
    handlePhoneInput(event) {
      let value = event.target.value
      // 只保留数字
      value = value.replace(/[^0-9]/g, '')
      // 限制长度为11位
      if (value.length > 11) {
        value = value.slice(0, 11)
      }
      // 更新数据
      this.formData.clerkPhone = value
      // 同步更新输入框的值
      event.target.value = value
    },
    
    // 获取URL参数
    getUrlParams() {
      const url = window.location.href
      const params = {}
      const urlParts = url.split('?')
      if (urlParts.length > 1) {
        const queryString = urlParts[1]
        const pairs = queryString.split('&')
        pairs.forEach(pair => {
          const [key, value] = pair.split('=')
          params[decodeURIComponent(key)] = decodeURIComponent(value || '')
        })
      }
      return params
    },
    
    // 跳转到微信授权页面
    redirectToWechatAuth() {
      console.log('执行跳转到微信授权页面')
      
      // 这里需要替换为您的实际配置
      const appId = 'wxb67c3175b93d1240' // 请替换为实际的微信公众号AppID
      
      // 检查AppID是否已配置
      if (appId === 'YOUR_WECHAT_APPID') {
        console.error('AppID未配置，请替换为真实的微信公众号AppID')
        uni.showModal({
          title: '配置错误',
          content: '微信公众号AppID未配置，请联系开发者',
          showCancel: false
        })
        this.authLoading = false
        return
      }
      
      const currentUrl = "https://m.chushouya.com/pages/clerk/sign"
      const redirectUri = encodeURIComponent(currentUrl)
      const scope = 'snsapi_base' // 静默授权，只获取openid
      const state = 'clerk_sign_' + Date.now() // 使用时间戳作为状态值
      
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
      
      console.log('当前URL:', currentUrl)
      console.log('重定向URI:', redirectUri)
      console.log('生成的授权URL:', authUrl)
      
      // 添加延迟确保日志输出
      setTimeout(() => {
        console.log('即将跳转到微信授权页面...')
        try {
          window.location.href = authUrl
        } catch (error) {
          console.error('跳转失败:', error)
          uni.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          })
        }
      }, 100)
    },
  
    
    // 表单提交处理
    async handleSubmit() {
      // 检查是否已获取openid
      if (!this.authCode) {
        uni.showToast({
          title: '请先完成微信授权',
          icon: 'none'
        })
        return
      }
      // 验证表单
      if (!this.formData.clerkName.trim()) {
        uni.showToast({
          title: '请输入工程师姓名',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.clerkPhone.trim()) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.formData.clerkPhone)) {
        uni.showToast({
          title: '请输入正确的手机号码格式',
          icon: 'none'
        })
        return
      }
      
      try {
        this.loading = true
        
        // 调用注册接口，包含openid
        await fetchClerkSign({
          clerkName: this.formData.clerkName,
          clerkPhone: this.formData.clerkPhone,
          authCode: this.authCode
        })
        
        uni.showToast({
          title: '注册成功！',
          icon: 'success'
        })
        
        // 重置表单
        // this.formData.clerkName = ''
        // this.formData.clerkPhone = ''
        
      } catch (error) {
        console.error('注册失败:', error)
        uni.showToast({
          title: '注册失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.register-page {
  position: relative;
  width: 750rpx;
  height: 1334rpx;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 1);
}

/* 右上角背景图片 */
.register-page::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 300rpx;
  height: 300rpx;
  background-image: url('https://image.chushouya.com/uploads/file/1754618364931_9i15hu.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: top right;
  z-index: 1;
  pointer-events: none;
}

/* 左下角背景图片 */
.register-page::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 300rpx;
  height: 300rpx;
  background-image: url('https://image.chushouya.com/uploads/file/1754618371604_ab6s8j.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: bottom left;
  z-index: 1;
  pointer-events: none;
}

/* 主容器 */
.main-container {
  width: 750rpx;
  height: 1334rpx;
}

/* 表单区域 */
.form-section {
  width: 750rpx;
  height: 1321rpx;
}

/* 头部标题组 */
.header-group {
  width: 404rpx;
  height: 136rpx;
  margin: 263rpx 0 0 6rpx;
}

/* 应用标题 */
.app-title {
  width: 404rpx;
  height: 136rpx;
  overflow-wrap: break-word;
  color: rgba(247, 247, 251, 1);
  font-size: 144rpx;
  font-family: Adobe Heiti Std R;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 144rpx;
}

/* 页面副标题 */
.page-subtitle {
  width: 340rpx;
  height: 46rpx;
  overflow-wrap: break-word;
  color: rgba(29, 30, 44, 1);
  font-size: 48rpx;
  font-family: Adobe Heiti Std R;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 48rpx;
  margin: 80rpx 3rpx 0 -343rpx;
}

/* 姓名输入字段 */
.name-input-field {
  background-color: rgba(247, 247, 251, 1);
  border-radius: 8px;
  min-height: 108rpx;
  width: 622rpx;
  margin: 123rpx 0 0 64rpx;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

/* 电话输入字段 */
.phone-input-field {
  background-color: rgba(247, 247, 251, 1);
  border-radius: 8px;
  min-height: 108rpx;
  width: 622rpx;
  margin: 48rpx 0 0 64rpx;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

/* 输入框标签 */
.input-label {
  color: rgba(105, 112, 127, 1);
  font-size: 24rpx;
  font-family: Adobe Heiti Std R;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 24rpx;
  margin-bottom: 8rpx;
  flex-shrink: 0;
}

/* 输入框控件 */
.input-control {
  width: 100%;
  min-height: 48rpx;
  border: none;
  background: transparent;
  font-size: 32rpx;
  color: rgba(29, 30, 44, 1);
  padding: 8rpx 0;
  box-sizing: border-box;
  outline: none;
  flex: 1;
}

.input-control::placeholder {
  color: rgba(105, 112, 127, 0.6);
  font-size: 28rpx;
}

/* 提交按钮 */
.submit-button {
  background-color: rgba(250, 65, 105, 1);
  border-radius: 8px;
  height: 100rpx;
  width: 622rpx;
  margin: 64rpx 0 371rpx 64rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.submit-button:disabled {
  opacity: 0.6;
}

/* 按钮文字 */
.button-text {
  color: rgba(255, 255, 255, 1);
  font-size: 28rpx;
  font-family: Adobe Heiti Std R;
  font-weight: normal;
  text-align: center;
  white-space: nowrap;
  line-height: 28rpx;
}

/* 占位区域 */
.spacer-section {
  background-color: rgba(255, 255, 255, 0);
  width: 750rpx;
  height: 14rpx;
  margin: 1320rpx 0 0 -750rpx;
}

/* 微信授权加载状态 */
.auth-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner-wrapper {
  margin-bottom: 30rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(250, 65, 105, 0.2);
  border-top: 4rpx solid rgba(250, 65, 105, 1);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: rgba(105, 112, 127, 1);
  font-size: 28rpx;
  font-family: Adobe Heiti Std R;
  text-align: center;
}

/* 微信授权状态显示 */
.auth-status {
  margin: 40rpx 64rpx 20rpx 64rpx;
  padding: 20rpx;
  background-color: rgba(76, 175, 80, 0.1);
  border-radius: 8rpx;
  border-left: 6rpx solid rgba(76, 175, 80, 1);
}

.auth-success-text {
  color: rgba(76, 175, 80, 1);
  font-size: 26rpx;
  font-family: Adobe Heiti Std R;
  font-weight: 500;
}

/* Flex 布局辅助类 */
.flex-col {
  display: flex;
  flex-direction: column;
}

.flex-row {
  display: flex;
  flex-direction: row;
}
</style>